<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\District;
use Illuminate\Support\Facades\Auth;
use App\Repositories\DistrictRepository;
use App\Http\Requests\Common\District\ShowRequest;
use App\Http\Requests\Common\District\QueryResource;
use App\Http\Requests\Common\District\DistrictCreate;
use App\Http\Requests\Common\District\DistrictUpdate;
use App\Http\Requests\Common\District\DistrictDestroy;

class DistrictController extends Controller
{
    protected $districtRepository;

    /**
     * ArticlesController constructor.
     * @param DistrictRepository $districtRepository
     */
    public function __construct(
        DistrictRepository $districtRepository
    )
    {
        $this->districtRepository = $districtRepository;
    }

    /**
     * 获取地区资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $city_id = $request->get('city_id', false);
        $districts = $this->districtRepository->getDistricts($city_id);
        return success($districts);
    }

    /**
     * 获取地区详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, District $district)
    {
        return success($district);
    }


    /**
     * 创建地区
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param DistrictCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(DistrictCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $districts = $this->districtRepository->create($attributes);
        return stored($districts);
    }

    /**
     * 更新地区资源
     *
     * Date: 2018/05/11
     * @author Tenny
     * @param DistrictUpdate $request
     * @param district $district
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(DistrictUpdate $request, District $district)
    {
        $districtsAttr = $request->only([
            'district_name',
            'sort',
        ]);
        $district->update($districtsAttr);
        return updated($district);
    }

    /**
     * 删除 地区 资源
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param DistrictDestroy $request
     * @param District $district
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(DistrictDestroy $request, District $district)
    {
        $force = $request->get('force');
        $force ? $district->delete() : $district->forceDelete();
        return deleted();
    }
}
